package dsns.demo.springmvc.ctrls;

import java.util.Iterator;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller // 标记该类为Controller
@Scope("prototype") // 标记该类为多实例，默认为单例
public class DemoCtrl {
	
	// 映射请求路径到该方法
	// 普通请求
	@RequestMapping("/greeting")
	public ModelAndView normalRequestDemo(String greeting) {
		ModelAndView mv = new ModelAndView("greeting"); // View Resolver 见mvc.xml
		
		mv.addObject("greeting", greeting); // 类似request.setAttribute("greeting", greeting);
		
		return mv;
	}
	
	// 映射请求路径到该方法
	// AJAX返回
	@RequestMapping("/ajax")
	public ModelAndView ajaxRequestDemo(String greeting) {
		ModelAndView mv = new ModelAndView("greeting");
		
		mv.addObject("greeting", "Hello Ajax");
		
		return mv;
	}
	
	// 映射请求路径到该方法，只接受POST请求
	// 文件上传
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	public ModelAndView uploadRequestDemo(MultipartHttpServletRequest req) {
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		ModelAndView mv = new ModelAndView("greeting");
		if (isMultipart) {
			Iterator<String> it =  req.getFileNames();
	        MultipartFile mtf;
	        int i = 0;
	        while(it.hasNext()){
	            mtf = req.getFile(it.next()); 
	            mv.addObject("file_" + i++, "你上传的文件是：" + mtf.getOriginalFilename());
	        }
		}
		
		return mv;
	}
}
